//
//  PanHorizontalGestureRecognizer.m
//  TableViewCellLabs
//
//  Created by NicholasXu on 13-9-30.
//  Copyright (c) 2013年 Deheng.Xu. All rights reserved.
//

#import "PanHorizontalGestureRecognizer.h"

@interface PanHorizontalGestureRecognizer ()

@property (nonatomic) CGPoint beginPoint;
@property (nonatomic) CGPoint touchedPoint;
@property (nonatomic) CGFloat k;

@end

@implementation PanHorizontalGestureRecognizer


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.beginPoint = [touches.anyObject locationInView:self.view];
    self.touchedPoint = self.beginPoint;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint p = [touches.anyObject locationInView:self.view];
    
    if (p.x > self.touchedPoint.x) {
        self.gestureDirection = PanGestureRightDirection;
    }else if (p.x < self.touchedPoint.x) {
        self.gestureDirection = PanGestureLeftDirection;
    }else {
        self.gestureDirection = PanGestureNoneDirection;
    }
    
    if (self.state == UIGestureRecognizerStatePossible) {
        
        if (p.x - self.touchedPoint.x == 0) {
            self.k = 0;
        }else
        if (p.y - self.touchedPoint.y != 0) {
            self.k = (p.x - self.touchedPoint.x) / (p.y - self.touchedPoint.y);
        }else {
            self.k = CGFLOAT_MAX;
        }

        if (fabs(self.k) > 1.732) {//30 degree
            self.state = UIGestureRecognizerStateBegan;
        }
    }else if (self.state == UIGestureRecognizerStateBegan) {
        self.state = UIGestureRecognizerStateChanged;
    }else {
        self.state = UIGestureRecognizerStateChanged;
    }
    
    self.touchedPoint = [touches.anyObject locationInView:self.view];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.state == UIGestureRecognizerStateBegan ||
        self.state == UIGestureRecognizerStateChanged) {
        self.state = UIGestureRecognizerStateEnded;
    }
    else {
        self.state = UIGestureRecognizerStateFailed;
    }
    
//    self.touchedPoint = CGPointZero;
//    self.beginPoint = CGPointZero;
//    [self performSelector:@selector(reset) withObject:nil afterDelay:0.];
    [self reset];
    
#if DEBUG_GESTURE_LOGGING
    NSLog(@"%s", __func__);
#endif
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.state = UIGestureRecognizerStateCancelled;
    
    self.touchedPoint = CGPointZero;
    self.beginPoint = CGPointZero;
    
    //[self performSelector:@selector(reset) withObject:nil afterDelay:0.];
    [self reset];
#if DEBUG_GESTURE_LOGGING
    NSLog(@"%s", __func__);
#endif
}

- (void)reset
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(reset) withObject:nil waitUntilDone:YES];
        return;
    }
    
    self.state = UIGestureRecognizerStatePossible;
    
#if DEBUG_GESTURE_LOGGING
    NSLog(@"%s", __func__);
#endif
}

@end
